package cn.ztydata.teachingsystem.heaven.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 文件转换（office TO pdf）
 */
@Component
public class FileConverter {

    @Value("${rabbit.exchange}")
    private String exchange_name;

    @Value("${rabbit.queue}")
    private String queue_name;

    @Value("${rabbit.routeKey}")
    private String routeKey;

    @Autowired
    private ConnectionFactory connectionFactory;

    /**
     * 向队列中添加任务
     * @param task  需要转换的资源的数据主键
     * @throws IOException
     */
    public void newTask(String  task) throws IOException{
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        try {
            channel.exchangeDeclare(exchange_name, "topic");
            //设置通道每次只会保证消费端接受1个任务，直到接受到对应的ACK
            channel.basicQos(1);

            //声明队列: 持久化的
            channel.queueDeclare(queue_name, true, false, false, null);

            //把通道和队列进行绑定
            channel.queueBind(queue_name, exchange_name, routeKey);

            //把任务添加到rabbit中
            channel.basicPublish(exchange_name, "office.to.pdf",MessageProperties.PERSISTENT_TEXT_PLAIN, task.getBytes());
        }finally {
            channel.close();
            connection.close();
        }
    }
}

